package club.janna.jrpc.rpc.protocol.jrpc;

import club.janna.jrpc.remoting.Channel;
import club.janna.jrpc.remoting.ClientHandler;
import club.janna.jrpc.rpc.Callback;
import club.janna.jrpc.rpc.Invoker;
import club.janna.jrpc.rpc.RPCInvocation;
import club.janna.jrpc.rpc.RPCResponse;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author Panbo.Guo
 */
@Slf4j
public class JRPCInvoker implements Invoker, AutoCloseable {

    private Channel channel;
    private ClientHandler handler;

    /**
     * 关闭时的回调
     */
    private Callback onClose;

    /**
     * 引用计数
     */
    private AtomicInteger refCnt = new AtomicInteger(0);

    public JRPCInvoker(Channel channel, ClientHandler handler, Callback onClose) {
        this.channel = channel;
        this.handler = handler;
        this.onClose = onClose;
    }

    @Override
    public RPCResponse<?> invoker(RPCInvocation invocation) {
        Future<RPCResponse<?>> future = handler.register(invocation);
        channel.send(invocation);
        try {
            return future.get(5, TimeUnit.SECONDS);
        } catch (InterruptedException | TimeoutException | ExecutionException e) {
            log.error("调用远程服务出错，invocation -> {}", invocation, e);
            throw new RuntimeException("调用远程服务出错");
        }
    }

    /**
     * 引用
     */
    public void ref() {
        refCnt.incrementAndGet();
    }

    /**
     * 关闭
     */
    @Override
    public void close() {
        if(refCnt.decrementAndGet() == 0)
            onClose.call();
    }
}
